const nodemailer = require('nodemailer');
const moment = require('moment');
let color = require('chalk');

/**
 * send to mailBox
 * @param {string} email
 * @param {string} subject
 * @param {string} msg
 * @param {Function} callback
 */
function index(email, subject, msg, callback){
  new Promise((resolve,reject)=>{
    nodemailer.createTestAccount((err, account) => {
      // 填入自己的账号和密码
      let transporter = nodemailer.createTransport({
        host: 'smtp.163.com',
        port: 465,
        secure: true, // 如果是 true 则port填写465, 如果 false 则可以填写其它端口号
        auth: {
          user: "", // 发件人邮箱
          pass: "" // 发件人密码(用自己的...)
        }
      });
      // 获取当前时间
      //let sendTime = moment().format('MMMM Do YYYY, h:mm:ss a');
      // 填写发件人, 收件人
      let mailOptions = {
        // 发件人地址
        from: 'sfbrywj@163.com',
        to: email,
        // 邮件主题
        subject: subject,
        // 文字内容
        text: msg,
      };

      // 发送邮件
      transporter.sendMail(mailOptions, (error, info) => {
        console.log(color.cyan(`mailsender: ${color.hex('#ff00ff')(JSON.stringify(mailOptions))}`));
        if (error) {
          console.log(color.cyan(`mailsender: ${color.red(`send error: ${error}`)}`));
          reject(error);
        }
        console.log(color.cyan(`mailsender: ${color.green(`send success`)}`));
        resolve(info);
      });
    });
  }).then(()=>{callback(1)},(error)=>{callback(0)}).catch((error)=>{throw new Error(error)});
}
//
module.exports=index;